<?php
/**
 * 会员登录
 *
 *
 * @copyright  Copyright (c) 2007-2013 ShopNC Inc. (http://www.shopnc.net)
 * @license    http://www.shopnc.net
 * @link       http://www.shopnc.net
 * @since      File available since Release v1.1
 */
defined('InShopNC') or exit('Access Invalid!');

class loginControl extends MobileControl
{
    public function __construct()
    {
        parent::__construct();
    }

    public function indexOp()
    {
        /**
         * 实例化模型
         */
        $model_member = new memberModel();
        /**
         * 检查登录状态
         */
        $model_member->checkloginMember();

        if (chksubmit()) {
            if (cookie('tm_login') == 5) {
                mobileJump('您的操作过于频繁，请稍后再试', 'index.php');
            }
            Security::checkToken();

            $obj_validate = new Validate();
            $obj_validate->validateparam = array(
                array("input" => $_POST["user_name"], "require" => "true", "message" => '用户名/邮箱/已验证手机不能为空'),
                array("input" => $_POST["password"], "require" => "true", "message" => '密码不能为空'),
                array("input" => $_POST["captcha"], "require" => (C('captcha_status_login') ? "true" : "false"), "message" => '验证码不能为空'),
            );

            $error = $obj_validate->validate();
            if ($error != '') {
                mobileJump($error);
            } else {
                if (C('captcha_status_login')) {
                    if (!checkSeccode($_POST['nchash'], $_POST['captcha'])) {
                        mobileJump('验证码错误');
                    }
                }
                $array = array();
                $user_name = trim($_POST['user_name']);
                //$array['member_passwd']	= md5(trim($_POST['password']));
                //$member_info = $model_member->infoMember($array);
                $sql = "SELECT * FROM #__member WHERE member_name = '$user_name' OR member_mobile = '$user_name' OR member_email = '$user_name'";
                $member_info = Db::queryRow($sql);
                if (is_array($member_info) and !empty($member_info)) {
                    if ($member_info['member_passwd'] != md5(trim($_POST['password']))) {
                        mobileJump('密码输入错误');
                    }
                    setNcCookie('tm_login', '', -3600);
                    if (!$member_info['member_state']) {
                        mobileJump('您的账号已经被管理员禁用，请联系平台客服进行核实', 'index.php');
                    }
                    /**
                     * 登录时间更新
                     */
                    $update_info = array(
                        'member_login_num' => ($member_info['member_login_num'] + 1),
                        'member_login_time' => time(),
                        'member_old_login_time' => $member_info['member_login_time'],
                        'member_login_ip' => getIp(),
                        'member_old_login_ip' => $member_info['member_login_ip']);
                    $model_member->updateMember($update_info, $member_info['member_id']);
                    /**
                     * 写入session
                     */
                    $_SESSION['is_login'] = '1';
                    $_SESSION['is_seller'] = intval($member_info['store_id']) == 0 ? '' : 1;
                    $_SESSION['member_id'] = $member_info['member_id'];
                    $_SESSION['member_name'] = $member_info['member_name'];
                    $_SESSION['member_email'] = $member_info['member_email'];
                    $_SESSION['member_mobile'] = $member_info['member_mobile'];

                    if ($GLOBALS['setting_config']['qq_isuse'] == 1 && trim($member_info['member_qqopenid'])) {
                        $_SESSION['openid'] = $member_info['member_qqopenid'];
                    }
                    if ($GLOBALS['setting_config']['sina_isuse'] == 1 && trim($member_info['member_sinaopenid'])) {
                        $_SESSION['slast_key']['uid'] = $member_info['member_sinaopenid'];
                    }
                    //查询商城信息
                    if ($member_info['store_id'] > 0) {
                        $store_model = new storeModel();
                        $store_info = $store_model->shopStore(array('store_id' => $member_info['store_id']));
                        if (is_array($store_info) && count($store_info) > 0) {
                            $_SESSION['store_id'] = $store_info['store_id'];
                            $_SESSION['store_name'] = $store_info['store_name'];
                            $_SESSION['grade_id'] = $store_info['grade_id'];
                        }
                    }

                    //查询品牌商城信息
                    if ($member_info['brand_store_id'] > 0) {
                        $brand_store_model = new brand_storeModel();
                        $store_info = $brand_store_model->getBrandStoreInfo($member_info['brand_store_id']);
                        if (is_array($store_info) && count($store_info) > 0) {
                            $_SESSION['brand_store_id'] = $store_info['brand_store_id'];
                            $_SESSION['brand_store_name'] = $store_info['brand_store_name'];
                        }
                    }

                    // cookie中的cart存入数据库
                    $this->mergecart();

                    //添加会员积分
                    if (C('points_isuse')) {
                        //一天内只有第一次登录赠送积分
                        if (trim(@date('Y-m-d', $member_info['member_login_time'])) != trim(date('Y-m-d'))) {
                            $points_model = new pointsModel();
                            $points_model->savePointsLog('login', array('pl_memberid' => $member_info['member_id'], 'pl_membername' => $member_info['member_name']), true);
                        }
                    }
                    $evaluate_model = new evaluateModel();
                    $evaluate_model->updateMemberStat($_SESSION['member_id'], $_SESSION['store_id']);//统计更新:会员信用,卖家信用,商城评分
                    $_POST['ref_url'] = (strstr($_POST['ref_url'], 'logout') === false && !empty($_POST['ref_url'])) ? $_POST['ref_url'] : 'index.php?act=member_index';
                    if ($_POST['auto_login']) {
                        setNcCookie('atn', $user_name, 864000);
                        $p = encryptionAlgorithm(trim($_POST['password']));
                        setNcCookie('atp', $p, 864000);
                    }
                    /*检测是否显示现金券红包*/
                    memberModel::memberXjqShow($member_info['member_id']);
                    /*检测是否显示现金券红包*/
                    mobileJump('登录成功', $_POST['ref_url']);
                } else {
                    log_times('login');
                    mobileJump('登录失败');
                }
            }
        }
        if (C('captcha_status_login')) {
            Tpl::output('nchash', substr(md5(SiteUrl . $_GET['act'] . $_GET['op']), 0, 8));
        }
        if (empty($_GET['ref_url'])) $_GET['ref_url'] = getReferer();
        Tpl::output('html_title', C('site_name') . ' - 登&nbsp;&nbsp;&nbsp;录');
        Tpl::showpage('login');

    }

    /**
     * 退出操作
     *
     * @param int $id 记录ID
     * @return array $rs_row 返回数组形式的查询结果
     */
    public function logoutOp()
    {
        //loginModel::logout();
        session_unset();
        session_destroy();
        setNcCookie('uid', '', -3600);
        setNcCookie('rp_reg', '', -3600);
        setNcCookie('tm_login', '', -3600);
        setNcCookie('goodsnum', '', -3600);        // 进货车商品种数
        setNcCookie('atn', '', -3600);
        setNcCookie('atp', '', -3600);
        if (empty($_GET['ref_url'])) {
            $ref_url = getReferer();
        } else {
            $ref_url = $_GET['ref_url'];
        }
        mobileJump('退出成功', $ref_url);
    }

    /**
     * @desc 忘记密码页面
     */
    public function find_passwordOp()
    {
        Language::read('home_login_register');
        Tpl::output('nchash', substr(md5(SiteUrl . $_GET ['act'] . $_GET ['op']), 0, 8));
        Tpl::output('html_title', C('site_name') . ' - ' . Language::get('login_index_find_password'));
        Tpl::output('show_login_reg', 2);
        Tpl::showpage('find_password');
    }

    /**
     * @desc 找回密码验证邮箱或者手机号是否存在
     */
    public function find_password_email_existOp()
    {

        $email_or_mobile = trim($_GET['email']);

        if (empty($email_or_mobile))
            exit('false');

        $member_id = Db::queryRow("select member_id from #__member where member_email = '$email_or_mobile' or member_mobile = '$email_or_mobile' or member_name ='$email_or_mobile'");

        if ($member_id > 0)
            exit('true');

        exit('false');
    }

    /**
     * @desc 找回密码第二步
     */
    public function find_password_step2Op()
    {

        Language::read('home_login_register');
        $lang = Language::getLangContent();

        if ($_POST ['form_submit'] != 'ok') {
            mobileJump($lang ['login_password_enter_find'], 'index.php?act=login&op=forget_password');
        }

        if (!checkSeccode($_POST ['nchash'], $_POST ['captcha'])) {
            mobileJump($lang ['login_usersave_wrong_code'], '', 'html', 'error');
        }


        if (empty ($_POST ['email'])) {
            mobileJump($lang ['login_password_input_email'], '', 'html', 'error');
        }

        $email_or_mobile = trim($_POST ['email']);
        $member = Db::queryRow("select member_id, member_name, member_email, member_mobile from #__member where member_email = '$email_or_mobile' or member_mobile = '$email_or_mobile' or member_name = '$email_or_mobile'");

        if (empty($member)) {
            mobileJump('用户不存在', '', 'html', 'error');
        }

        $valid_list = array();
        foreach ($member as $k => $m) {
            if (empty($m))
                continue;

            if ($k == 'member_mobile')
                $valid_list['mobile'] = $m;

            if ($k == 'member_email')
                $valid_list['email'] = $m;
        }


        Tpl::output('valid_list', $valid_list);
        Tpl::output('member', $member);
        Tpl::showpage('find_password_step2');
    }

    /**
     * @desc 发送手机或则邮箱验证码
     */
    public function ajax_send_mobile_codeOp()
    {

        Language::read('home_login_register');
        $lang = Language::getLangContent();

        if (isset($_SESSION['member_login_find_password_time']) && time() - $_SESSION['member_login_find_password_time'] < 60) {
            exit(json_encode(array('msg' => '很抱歉，60秒内只能获取一次校验码，请您稍后再试', 'rs' => false)));
        }

        if (empty ($_POST ['member_id']) || empty($_POST['valid_mode'])) {
            exit(json_encode(array('msg' => '参数错误', 'rs' => false)));
        }

        $member_id = (int)$_POST['member_id'];
        $valid_mode = trim($_POST['valid_mode']);
        $field['mobile'] = 'member_mobile';
        $field['email'] = 'member_email';

        //获取用户信息
        $member_info = Db::queryRow("select {$field[$valid_mode]},member_name from #__member where member_id = $member_id");
        $email_or_mobile = $member_info[$field[$valid_mode]];
        $find_password_captcha = rand(100000, 999999);

        //发送邮件验证码
        if ($valid_mode == 'email') {

            $result = noticeModel::system_send_notice($member_id, 'email_touser_find_password', array(
                'site_name' => $GLOBALS ['setting_config'] ['site_name'],
                'site_url' => SiteUrl,
                'user_name' => $member_info ['member_name'],
                'find_password_captcha' => $find_password_captcha
            ), false);

            // 发送手机验证码
        } elseif ($valid_mode == 'mobile') {

            $result = mobileModel::send($email_or_mobile, '正在使用找回密码功能，您的验证码是' . $find_password_captcha . '，如非本人操作无需理会本条信息');
        }

        if ($result) {
            $_SESSION['member_login_find_password_captcha'] = $find_password_captcha;
            $_SESSION['member_login_find_password_id'] = $member_id;
            $_SESSION['member_login_find_password_time'] = time();
            exit(json_encode(array('rs' => true)));
        } else {
            exit(json_encode(array('rs' => false, 'msg' => '服务器忙，请重新再试')));
        }
    }

    /**
     * @desc 检查校验码
     */
    public function check_find_password_codeOp()
    {

        $code = trim($_POST['code']);

        if ($code != $_SESSION['member_login_find_password_captcha']) {
            exit(json_encode(array('rs' => false, 'msg' => '校验码错误')));
        }

        exit(json_encode(array('rs' => true)));
    }

    /**
     * @desc 找回密码第三步
     */
    public function find_password_step3Op()
    {

        $code = trim($_POST['code']);

        if ($code != $_SESSION['member_login_find_password_captcha']) {
            mobileJump('校验码不正确', '', 'html', 'error');
        }

        $member_id = $_SESSION['member_login_find_password_id'];
        if (empty($member_id)) {
            mobileJump('无法获取用户信息，请重新再试', '', 'html', 'error');
        }

        Tpl::showpage('find_password_step3');
    }

    /**
     * @desc 找回密码第四步
     */
    public function find_password_step4Op()
    {

        $new_password = trim($_POST['new_password']);

        if (empty($new_password)) {
            mobileJump('参数错误', '', 'html', 'error');
        }

        $member_id = $_SESSION['member_login_find_password_id'];
        if (empty($member_id)) {
            mobileJump('无法获取用户信息，请重新再试', '', 'html', 'error');
        }

        $result = Db::update('member', array('member_passwd' => md5($new_password)), "member_id = $member_id");

        unset($_SESSION['member_login_find_password_captcha']);
        unset($_SESSION['member_login_find_password_id']);
        unset($_SESSION['member_login_find_password_time']);

        if (!$result)
            mobileJump('修改密码失败，请重新再试', '', 'html', 'error');

        Tpl::showpage('find_password_step4');
    }

}
